package com.lzx.reggie.controller

import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.lzx.reggie.common.R
import com.lzx.reggie.entity.User
import com.lzx.reggie.service.UserService
import com.lzx.reggie.utils.ValidateCodeUtils
import org.apache.commons.lang.StringUtils
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import javax.servlet.http.HttpSession


@RestController
@RequestMapping("/user")

class UserController {
    companion object {
        private val log = LoggerFactory.getLogger(UserController::class.java)
    }

    @Autowired
    private lateinit var userService: UserService

    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    fun sendMsg(@RequestBody user: User, session: HttpSession): R<Any> {
        //获取手机号
        val phone = user.phone
        if (StringUtils.isNotEmpty(phone)) {
            //生成随机的4位验证码
            val code = ValidateCodeUtils.generateValidateCode(4).toString()
            log.info("code={}", code)

            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖","",phone,code);

            //需要将生成的验证码保存到Session
            session.setAttribute(phone, code)
            return R.success("手机验证码短信发送成功")
        }
        return R.error("短信发送失败")
    }

    /**
     * 移动端用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    fun login(@RequestBody map: Map<*, *>, session: HttpSession): R<Any> {
        log.info(map.toString())

        //获取手机号
        val phone = map["phone"].toString()

        //获取验证码
        val code = map["code"].toString()

        //从Session中获取保存的验证码
        val codeInSession = session.getAttribute(phone)

        //进行验证码的比对（页面提交的验证码和Session中保存的验证码比对）
        if (codeInSession != null && codeInSession == code) {
            //如果能够比对成功，说明登录成功
            val user = userService.getOne(
                KtQueryWrapper(User::class.java).apply {
                    eq(User::phone, phone)
                })
            session.setAttribute("user", user.id)
            return R.success(user)
        }
        return R.error("登录失败")
    }
}
